import java.net.*;
import java.util.Scanner;
import javax.swing.JPanel;
import java.io.*;


public class Main extends JPanel implements Runnable{
	public static boolean isHost;
	Player player;
	GameBoard board;
	GameServer server;
	Socket s;
	Scanner input;
	
	
	//Threadz
	Thread gameThread; // This makes the game stuff work
	Thread main; // This is for when we want to draw otherwise
	Thread currentThread;
	

	public Main(int numberOfPlayers) {
		isHost = true; 
		
		player = new Player(0);
		server = new GameServer();
		
		try {
			s = new Socket(server.getServer().getInetAddress(), 42170);
			input = new Scanner(s.getInputStream());
			board = new GameBoard(numberOfPlayers, player, s);
		} catch(Exception e) {}
		player.setBoard(board);
		
		gameThread = new Thread(board);
		
	}
	
	public Main(int numberOfPlayers, String ip, int id) {
		isHost = false;
		
		player = new Player(id);
		server = null;
		
		try{
			s = new Socket(ip, 42170);
			input = new Scanner(s.getInputStream());
			board = new GameBoard(numberOfPlayers, player, s);
		} catch (Exception e) {}
		
		player.setBoard(board);
		
		gameThread = new Thread(board);
	}
	
	public void run() {
		try{
			if(currentThread == gameThread) {
				board.setState(parseInput(input.nextLine()));
				currentThread = main;
			}
			if(currentThread == main) {
				disp(); // update the screen
			}
			currentThread.sleep(100);
		}catch(Exception e) {}
	}
	
	public char parseInput(String s) {
		if(s.contains("GAME")) {
			String[] temp = s.split("GAME");
			board.setGame(Integer.parseInt(temp[temp.length - 1]), false)
			return 'g';
		}
		if(s.contains("REFRESH"))
			return 'a';
		if(s.contains("END")) // rememeber to write in Game
			return 'e';
		if(s.contains("P")) {
			if(player.id != (int)s.charAt(s.indexOf("P")) + 1) 
				return 'd';
			String score = "";
			char[] temp = s.toCharArray();
			for(int i = 0; i < temp.length; i++) {
				if((int)temp[i] >= 48 && (int)temp[i] <= 57) {
					if((int)temp[i - 1] == 'S') {
						while((int)temp[i] != 'S') {
							score += temp[i+1];
							i++;
						}
					}
				}
			}
			player.increaseScore(Integer.parseInt(score));
		}
		return 'd';
		
	}
		
	public void disp() {
		
	}
	/* STANDARD DATA TRANSFER
	 * PNSXXXXXXS - Player N, Score XXXXXXX
	 * REFRESH - This tells the computer to refresh GameBoard
	 * GAME - Start Game from GameBoard
	 * END - End game 
	 * */
}
